package corewarsxxi.logic;

import corewarsxxi.logic.throwables.processHalt;
import corewarsxxi.logic.throwables.processJump;
import java.io.Serializable;

/**
 *
 * @author ei10139
 */
public class Process implements Serializable
{
    /**Number of cycles the process has performed. */
    public int cycleCount = 0;

    /**The offset where the process is currently at.*/
    public int offset = 0;

    /**
     * Constructs a new process at the speficied offset.
     * @param offset MemoryArray offset
     */
    public Process(int offset)
    {
        this.offset = offset;
    }

    /**
     * Performs a cycle by executing an instruction
     * and updating its offset accordingly.
     *
     * @throws processHalt in case the process has died
     */
    public void cycle() throws processHalt
    {
        ++cycleCount;
        
        // do operation
        MemoryCell mc = Core.getInstance().memArray.get(offset);
        
        try
        {
            mc.opCode.operation(mc.aField, mc.bField);
            offset++;
        }
        catch(processJump jp)
        {
            if(jp.relative)
                offset += jp.offset;
            else
                offset = jp.offset;
        }
    }
}
